<template>
  <view class="container">
    <uni-nav-bar class="navBar_cnt" left-icon="left" title="购物车"
                 @clickLeft="clickLeft"
                 :fixed="true" :border="false" :statusBar="true"
    >
      <template v-slot:right>
        <view class="edit_cnt" :class="{isEdit}" @click="handleEdit">{{ isEdit ? '完成' : '编辑' }}</view>
      </template>
    </uni-nav-bar>
    <!--		<view class="header">-->
    <!--			<view class="title1">-->
    <!--				<scroll-view class="scroll-view-box" scroll-y="true">-->
    <!--					<z-tabs ref="tabs" class='tabs' :list="partition" :current="isSingle" @change="onClickItem"-->
    <!--						active-color="#00C356"></z-tabs>-->
    <!--					&lt;!&ndash; <uni-segmented-control :current="isSingle" :values="partition"  @clickItem="onClickItem" styleType="text" activeColor="#00C356"></uni-segmented-control> &ndash;&gt;-->
    <!--				</scroll-view>-->
    <!--			</view>-->
    <!--			<view class="title2">-->
    <!--				已选<text>{{checklist}}</text>件，总共{{checktotal}}件商品-->
    <!--			</view>-->
    <!--		</view>-->
    <empty v-if="goodslist.length==0"></empty>
    <uni-swipe-action>
      <checkbox-group @change="checkboxChange">
        <block v-for="(items,index) in goodslist" :key="index">
          <label>
            <view class="box_cnt">
              <view class="box">
<!--                <view class="business">-->
<!--                  								<image :src="(items.goods.business&&items.goods.business.shop_head)||$store.state.logo" mode="aspectFill"></image>-->
<!--                  {{(items.goods.business&&items.goods.business.name)|| $store.state.name}}-->
<!--                </view>-->
                <view class="">
                  <uni-swipe-action-item :right-options="options" @click="bindClick(value,items.ID)">
                    <view class="goodsbox">
                      <checkbox
                          :value="items" iconColor="#FF4A01"
                                borderColor="#FF4A01"
                                activeBorderColor="#FF4A01" :checked="items.ischecked" @click="handcheck(index)"
                                />
                      <view class="goods"  >
                        <image class="image " :src="items.goods.img" mode="aspectFill"></image>
                        <view class="right">
                          <view class="name textsl2" @click.stop="gogoodsdetail(items.goods.ID)">
                            {{items.goods.name}}
                          </view>
                          <view class="gg">
                            规格: <text v-for="(itemss,index) in items.attribute"
                                        :key="index">{{itemss.val}}</text>
                          </view>
                          <view class="num" @click.stop="">
                            <text class="prcie">￥{{items.price}}</text>
                            <uni-number-box
                                @change="(value)=>{bindChange(items.ID,index,items,value)}"
                                v-model="items.number"  />
                          </view>
                        </view>
                      </view>
                    </view>
                  </uni-swipe-action-item>
                </view>
              </view>
            </view>
          </label>
        </block>
      </checkbox-group>
    </uni-swipe-action>
    <view class="" style="height: 260rpx;">
    </view>
    <!-- #ifndef H5 -->
    <view class="footer" :style="{bottom:'0'}">
      <view class="left">
        <checkbox-group @change="setcheck">
          <label class="checkbox">
            <checkbox iconColor="#FF4A01"
                                borderColor="#FF4A01"
                                activeBorderColor="#FF4A01"  :value="selectAll" :checked="selectAll.ischecked"/>
            全选
          </label>
        </checkbox-group>
      </view>
      <view class="right" v-if="!isEdit">
        <view class="lefts">
          <view class="top">
            <text>合计：</text>
            <text class="totalMoney text_5_30 text_c_r">￥{{ $formatMoney(totalMoney, 2) }}</text>
          </view>

        </view>
        <view class="rights" @click="submit">
          结算
        </view>
      </view>
      <view class="right" v-else>
        <view class="rights delete" @click="delFn">
          删除
        </view>
      </view>
    </view>
    <!-- #endif -->
    <!-- #ifdef H5 -->
    <view class="footer"  :style="{bottom:'0'}">
      <view class="left">
        <checkbox-group @change="setcheck">
          <label class="checkbox">
            <checkbox iconColor="#FF4A01"
                                borderColor="#FF4A01"
                                activeBorderColor="#FF4A01"  :value="selectAll" :checked="selectAll.ischecked"/>
            全选
          </label>
        </checkbox-group>
      </view>
      <view class="right" v-if="!isEdit">
        <view class="lefts">
          <view class="top">
            <text>合计：</text>
            <text class="totalMoney text_5_30 text_c_r">￥{{ $formatMoney(totalMoney, 2) }}</text>
          </view>

        </view>
        <view class="rights" @click="submit">
          结算
        </view>
      </view>
      <view class="right" v-else>
        <view class="rights delete" @click="delFn">
          删除
        </view>
      </view>
    </view>
    <!-- #endif -->
    <!--		&lt;!&ndash; #ifndef H5 &ndash;&gt;-->
    <!--		<view class="footer" :style="{bottom:'0'}">-->
    <!--			<view class="left">-->
    <!--				<checkbox-group @change="setcheck">-->
    <!--					<label class="checkbox">-->
    <!--						<checkbox color="#00C356" value="全选" :checked="ischecked" />全选-->
    <!--					</label>-->
    <!--				</checkbox-group>-->
    <!--			</view>-->
    <!--			<view class="right">-->
    <!--				<view class="lefts">-->
    <!--					<view class="top">-->
    <!--						<text>免运费</text><text>合计：</text><text>{{totalMoney}}</text>-->
    <!--					</view>-->
    <!--					<view class="bottom">-->
    <!--						<text>共减{{discount}}</text>-->
    <!--					</view>-->
    <!--				</view>-->
    <!--				<view class="rights" @click="submit">-->
    <!--					结算-->
    <!--				</view>-->
    <!--			</view>-->
    <!--		</view>-->
    <!--		&lt;!&ndash; #endif &ndash;&gt;-->
    <!--		&lt;!&ndash; #ifdef H5 &ndash;&gt;-->
    <!--		<view class="footer" :style="{bottom:$isIos()?'50px':'50px'}">-->
    <!--			<view class="left">-->
    <!--				<checkbox-group @change="setcheck">-->
    <!--					<label class="checkbox">-->
    <!--						<checkbox color="#00C356" value="全选" :checked="ischecked" />全选-->
    <!--					</label>-->
    <!--				</checkbox-group>-->
    <!--			</view>-->
    <!--			<view class="right">-->
    <!--				<view class="lefts">-->
    <!--					<view class="top">-->
    <!--						<text>合计：</text><text>{{totalMoney}}</text>-->
    <!--					</view>-->
    <!--					<view class="bottom">-->
    <!--						<text>共减{{discount}}</text>-->
    <!--					</view>-->
    <!--				</view>-->
    <!--				<view class="rights" @click="submit">-->
    <!--					结算-->
    <!--				</view>-->
    <!--			</view>-->
    <!--		</view>-->
    <!--		&lt;!&ndash; #endif &ndash;&gt;-->
  </view>
</template>

<script setup>
import {
  ref,
  reactive,
  getCurrentInstance,
  customRef,
} from "vue";
import {
  onLoad,
  onShow
} from "@dcloudio/uni-app";


import {
  useStore
} from 'vuex'
//#region  Vuex
let store = useStore();
let state = store.state;
const clickLeft=()=>{
  uni.navigateBack()
}
const gogoodsdetail = (id) => {
  uni.navigateTo({
    url: '/pages/commodity/details?id=' + id
  })
}
const isEdit = ref(false)
/**
 * 编辑
 */
const handleEdit = () => {
  isEdit.value = !isEdit.value
  // setcheck()

}

// 删除
const delFn  = () => {
  let list = JSON.parse(JSON.stringify(goodslist.value))
  let attribute_list = []
  // for (let key in list) {
  // 	list[key].forEach(item => {
  // 		if (item.ischecked) {
  // 			attribute_list.push({
  // 				price_id: item.attribute_id,
  // 				number: item.number
  // 			})
  // 		}
  // 	})
  // }
  list.forEach(item => {
    if (item.ischecked) {
      attribute_list.push(+item.ID)
    }
  })
  if (attribute_list.length == 0) {
    uni.showToast({
      icon: 'none',
      title: '请选择商品'
    })
    return
  }
  bindClick(1, attribute_list)
}









const selectAll=ref({
  ischecked:false
})
// >>>>>>>>
const {
  proxy
} = getCurrentInstance();

let options = reactive([{
  text: '删除',
  style: {
    backgroundColor: 'red'
  }
}])
let isSingle = ref(0)
let partition = ref([])
let partitionList = reactive([])
let checklist = ref(0)
let checktotal = ref(0)
let goodslist = ref([])
let ischecked = ref(true)
let totalMoney = ref(0)
let isdisabled = ref(false)
let discount = ref(0)
let query = reactive({
  page: 0,
  pages: 1,
  size: 10,
})

function setcheck(e) {

  totalMoney.value = 0
  discount.value = 0
  if (e.detail.value.length == 1) {
    checklist.value = goodslist.value.length
    let list = JSON.parse(JSON.stringify(goodslist.value))
    console.log(list, "list1")
    for (let key in list) {
      // list[key].forEach(item => {
      // 	item.ischecked = true
      // 	totalMoney.value = totalMoney.value + (item.price * item.number)
      // })
      list[key].ischecked = true
      totalMoney.value = totalMoney.value + (list[key].price * list[key].number)
      discount.value = discount.value + (list[key].goods.market * list[key].number)
    }
    goodslist.value = list
    ischecked.value = true
  } else {
    checklist.value = 0
    totalMoney.value = 0
    discount.value = 0
    let list = JSON.parse(JSON.stringify(goodslist.value))

    for (let key in list) {
      console.log(list[key], key, "list2")
      // list[key].forEach(item => {
      // 	item.ischecked = false
      // })
      list[key].ischecked = false
    }

    goodslist.value = list
    // goodslist.value.forEach(item => {
    // 	item.forEach(items=>{
    // 	items.ischecked = false
    // })
    // })
    ischecked.value = false
  }
}
onLoad((option) => {})
onShow(() => {
  partitionList = uni.getStorageSync("partition")
  Getpartition()
})

function Getpartition() {
  proxy.$request({
    url: `api/partition/?page=1&size=50`,
    method: 'get',
    success: (res) => {
      partitionList = res.data.data
      uni.setStorageSync("partition", partitionList)
      partition.value = partitionList.map(item => {
        return item.name
      })
      getGoods()
    }
  })
}

function onClickItem(e) {
  isSingle.value = e
  getGoods()
}

function getGoods() {
  proxy.$request({
    url: `api/shoppingCart/?page=${query.page}&size=${query.size}`,
    method: 'get',
    data: {
      page: query.page,
      size: query.size
    },
    success: (res) => {
      let list = res.data.data
      checklist.value = 0
      totalMoney.value = 0
      checktotal.value = 0
      discount.value = 0
      list.forEach(item => {
        item['ischecked'] = true
        checklist.value = checklist.value + 1
        checktotal.value = checktotal.value + 1
        totalMoney.value = totalMoney.value + (item.price * item.number)
        discount.value = discount.value + (item.goods.market * item.number)
      })
      // for (let key in list) {
      // 	list[key].forEach(item => {
      // 		item['ischecked'] = true
      // 		checklist.value = checklist.value + 1
      // 		checktotal.value = checktotal.value + 1
      // 		totalMoney.value = totalMoney.value + (item.price * item.number)
      // 	})
      // }
      goodslist.value = list
    }
  })


}

function bindClick(e, idS) {
  if(!Array.isArray(idS)){
    idS = [idS]
  }
  proxy.$request({
    url: `api/shoppingCart/`,
    method: 'DELETE',
    data: {
      id_list:idS
    },
    success: (res) => {
      if (res.errno == 0) {
        // uni.showToast({
        // 	icon: res.errmsg
        // })
        getGoods()

      }


    }
  })
}
const handChange = debounce(function(ID, index, obj, e) {
  bindChange(ID, index, obj, e)
  console.log("handChange", ID, index, obj, e)
}, 500)


function bindChange(ID, index, obj, newValue) {
  // 1. 保存原始值（关键步骤）
  const originalNumber = obj.number; 

  proxy.$request({
    url: `api/shoppingCart/`,
    method: 'PUT',
    data: { id: ID, number: newValue },
    success: (res) => {
      if (res.errno === 0) {
        // 正常处理逻辑
        if (obj.number === 0) bindClick(e, ID);
        else getGoods();
      }
    },
    fail: (err) => {
      console.error("请求失败:", err);
      // 2. 失败时恢复原始值
      obj.number = originalNumber; 
      
      // 可选：触发视图强制更新（Vue响应式系统通常自动处理）
      // 仅在严格模式下需要，大多数情况可省略
      // if (proxy.$forceUpdate) proxy.$forceUpdate();
    }
  })
}
//防抖节流
function debounce(fn, delay) {
  let timer = null;
  return function() {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(this, arguments);
    }, delay);
  };
}


function checkboxChange(e) {
  checklist.value = e.detail.value.length
  totalMoney.value = 0
  discount.value = 0
  e.detail.value.forEach(item => {
    totalMoney.value = totalMoney.value + (item.price * item.number)
    discount.value = discount.value + (item.goods.market * item.number)
  })
  if (e.detail.value.length == checktotal.value) {
    ischecked.value = true
  } else {
    ischecked.value = false
  }
}

function handcheck(i) {
  goodslist.value[i].ischecked = !goodslist.value[i].ischecked
}

function submit() {
  const user=uni.getStorageSync("userInfo")
  if(!user.username){
    uni.showToast({
      icon: 'none',
      title: '请先实名认证'
    })
    uni.navigateTo({
      url:"/pages/personal/realName/realName"
    })
    return;
  }
  let list = JSON.parse(JSON.stringify(goodslist.value))
  let attribute_list = []
  // for (let key in list) {
  // 	list[key].forEach(item => {
  // 		if (item.ischecked) {
  // 			attribute_list.push({
  // 				price_id: item.attribute_id,
  // 				number: item.number
  // 			})
  // 		}
  // 	})
  // }
  const noStockList = []
  list.forEach((item,index) => {
    if (item.ischecked) {
      if(item.goods.stock==0){
        noStockList.push({index:index+1,...item})
      }

      attribute_list.push({
        price_id: item.attribute_id,
        number: item.number
      })
    }
  })
  if(noStockList.length>0){
    uni.showToast({
      icon: 'none',
      title: '第'+noStockList.map(item=>(`${item.index}`)).join(",")+'件商品请到线下店铺购买'
    })
    return;
  }
  // let attribute_list=JSON.parse(JSON.stringify(checklist.value)).map(item=>{
  // 	return {
  // 		price_id:item.attribute_id,
  // 		number:item.number
  // 	}
  // })
  if (attribute_list.length == 0) {
    uni.showToast({
      icon: 'none',
      title: '请选择商品'
    })
    return
  }
  proxy.$request({
    url: `api/order/`,
    method: 'post',
    data: {
      'attribute_list': attribute_list
    },
    success: (res) => {
      if (res.errno == 0) {
        proxy.$goURl('/pages/order/createorder?id=' + res.data)
      } else {
        uni.showToast({
          icon: 'none',
          title: res.errmsg
        })
      }
    }
  })
}
</script>

<style lang="scss" scoped>
page {
  background-color: #fff;
}

.container {
  .header {
    background-color: #fff;
    padding: 0rpx 30rpx 30rpx 30rpx;

    .title1 {
      color: #333;
      font-size: 48rpx;
      font-weight: bold;
    }

    .title2 {
      font-size: 24rpx;
      color: #999999;
      margin-top: 20rpx;

      text {
        color: $color1;
      }
    }
  }

  .goodsbox {
    border-radius: 30rpx;
    background-color: #fff;
    display: flex;
    align-items: center;
    //padding-left: 30rpx;
    // margin: 15rpx 20rpx;

    .goods {
      display: flex;
      padding: 20rpx 5rpx;
      width: 100%;

      .image {
        width: 196rpx;
        height: 196rpx;
        //border-radius: 30rpx;
        margin-right: 30rpx;
      }

      .right {
        width: calc(100% - 230rpx);

        .name {
          color: #333333;
          font-size: 32rpx;
          font-weight: bold;
        }

        .gg {
          color: #999999;
          font-size: 24rpx;
          margin: 20rpx 0;
        }

        .num {
          color: #999999;
          font-size: 24rpx;
          display: flex;
          justify-content: space-between;
          align-items: center;

          .prcie {
            color: #F63B29;
            font-size: 28rpx;
          }
        }
      }
    }
  }

  .footer {
    width: calc(100% - 60rpx);
    padding: 30rpx;
    background-color: #fff;
    position: fixed;
    bottom: 50px;
    left: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .left {
      .checkbox {
        display: flex;
        align-items: center;
      }
    }

    .right {
      display: flex;
      align-items: center;

      .lefts {
        margin-right: 20rpx;
        .bottom {
          display: flex;
          justify-content: flex-end;

          text:nth-child(1) {
            color: #333;
            font-size: 24rpx;
          }

          text:nth-child(2) {
            color: $color1;
            font-size: 24rpx;
            margin-left: 10rpx;
          }
        }
      }

      .rights {
        color: #fff;
        width: 164rpx;
        height: 70rpx;
        background: #F63B29;
        border-radius: 16rpx 16rpx 16rpx 16rpx;
        box-sizing: border-box;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .delete{
        background: #F96666;
      }
    }
  }
}
.box_cnt{
  padding:0 30rpx;
  background-color: #fff;

}
.box {
  //margin: 20rpx;
  //border-radius: 20rpx;
  padding: 40rpx 0;

  border-bottom: 1rpx solid #E0E0E0;
  .business {
    display: flex;
    font-weight: bold;
    align-items: center;

    image {
      width: 50rpx;
      height: 50rpx;
      border-radius: 50%;
      margin-right: 10rpx;
    }
  }
}

::v-deep .z-tabs-item {
  flex: none !important;
}
:deep(.uni-checkbox-input){
  width: 32rpx;
  height: 32rpx;
}
::v-deep .uni-checkbox-input {
  border-radius: 50% !important;
  border-color: #FF4A01 !important;
  border-width: 3rpx !important;
}
.totalMoney{
  color: #F63B29;
}
</style>
